package main

import (
	"fmt"
	"net"
	"sort"

	"bytes"
	"encoding/binary"
)

func intToByte(n int) []byte {
	data := int64(n)
	bytebuffer := bytes.NewBuffer([]byte{})

	binary.Write(bytebuffer, binary.BigEndian, data)

	return bytebuffer.Bytes()
}

func byteToInt(bts []byte) int {

	bytebuffer := bytes.NewBuffer(bts)
	var data int64
	binary.Read(bytebuffer, binary.BigEndian, &data)

	return int(data)
}

// 服务器端
func main() {
	server_listenrs, err := net.Listen("tcp", "127.0.0.1:7002")

	if err != nil {
		panic(err)
	}

	defer server_listenrs.Close() //延迟关闭

	for {
		conn, err := server_listenrs.Accept() //接受消息
		if err != nil {
			fmt.Println(err)
			break
		}

		go MsgHandler(conn)
	}
}

func MsgHandler(conn net.Conn) {
	buf := make([]byte, 16)
	defer conn.Close()
	arr := []int{} //数组保存数据

	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("client close ")
			return
		} else {

			if n == 16 {
				data1 := byteToInt(buf[:len(buf)/2])
				data2 := byteToInt(buf[len(buf)/2:])

				fmt.Println(data1, data2)

				if data1 == 0 && data2 == 0 {
					arr = make([]int, 0, 0) //开辟数据
				}

				if data1 == 1 {
					arr = append(arr, data2)
				}

				if data1 == 0 && data2 == 1 {
					fmt.Println("数组接收完成", arr)

					sort.Ints(arr) //排序
					fmt.Println("数组排序完成", arr)

					//写入
					mybstart := intToByte(0)
					mybstart = append(mybstart, intToByte(0)...)
					conn.Write(mybstart)

					for i := 0; i < len(arr); i++ {
						mybdata := intToByte(1)
						mybdata = append(mybdata, intToByte(arr[i])...)
						conn.Write(mybdata)
					}

					mybend := intToByte(0)
					mybend = append(mybend, intToByte(1)...)
					conn.Write(mybend)

					arr = make([]int, 0, 0) //开辟数据

				}
			}
		}
	}

}
